# -*- coding: utf8  -*-
import os
import copy
import logging
import logging.config
try:
    import configparser
except:
    import ConfigParser as configparser
from .log_conf import get_basic_log_settings
from logging import LoggerAdapter
import socket
import getpass

MACHINE_NAME = socket.getfqdn(socket.gethostname())
USER_NAME = getpass.getuser()
BASE = "Base"
LOG_DIR = "log_dir"
LOG_FILE = "log_file"
LOG_LEVEL = "log_level"
required_ops = [(BASE, LOG_DIR), (BASE, LOG_FILE), (BASE, LOG_LEVEL)]


class LoggerAdapterCustomer(LoggerAdapter):
    """
    An adapter for loggers which makes it easier to specify contextual
    information in logging output.
    cpython haven't warn
    """
    def __init__(self, logger, extra):
        LoggerAdapter.__init__(self, logger, extra)

    def warn(self, msg, *args, **kwargs):
        """
        Delegate a warning call to the underlying logger, after adding
        contextual information from this adapter instance.
        """
        msg, kwargs = self.process(msg, kwargs)
        self.logger.warning(msg, *args, **kwargs)


def init_log_from_config(cfg_file, formatter='standard'):
    parser = configparser.ConfigParser()
    parser.read(cfg_file)
    for sec, op in required_ops:
        if not parser.has_option(sec, op):
            raise Exception("Log load config file failed")
    log_dir = parser.get(BASE, LOG_DIR)
    log_file = parser.get(BASE, LOG_FILE) + '.' + MACHINE_NAME
    log_level = parser.get(BASE, LOG_LEVEL)
    settings = get_basic_log_settings()
    settings['handlers']['info_handler']['filename'] = log_dir + '/' + log_file + '.info'
    settings['handlers']['debug_handler']['filename'] = log_dir + '/' + log_file + '.debug'
    settings['handlers']['warn_handler']['filename'] = log_dir + '/' + log_file + '.warn'
    settings['handlers']['error_handler']['filename'] = log_dir + '/' + log_file + '.error'
    if formatter == 'flume':
        settings['handlers']['info_handler']['formatter'] = formatter
        settings['handlers']['debug_handler']['formatter'] = formatter
        settings['handlers']['warn_handler']['formatter'] = formatter
        settings['handlers']['error_handler']['formatter'] = formatter
    settings['loggers'][log_file] = copy.deepcopy(settings['loggers']['dxm'])
    logging.config.dictConfig(settings)
    extra_dict = {"host": MACHINE_NAME}
    logger = logging.getLogger(log_file)
    logger.propagate = False
    if log_level == 'DEBUG':
        logger.setLevel(logging.DEBUG)
    elif log_level == 'INFO':
        logger.setLevel(logging.INFO)
    elif log_level == 'WARN':
        logger.setLevel(logging.WARN)
    elif log_level == 'ERROR':
        logger.setLevel(logging.ERROR)
    else:
        raise "unknown log level:[%s]"

    return LoggerAdapterCustomer(logger, extra_dict)


def init_log_for_every_user(cfg_file, formatter='standard'):
    parser = configparser.ConfigParser()
    parser.read(cfg_file)
    for sec, op in required_ops:
        if not parser.has_option(sec, op):
            raise Exception("Log load config file failed")
    log_dir = parser.get(BASE, LOG_DIR)
    if os.access(log_dir, os.W_OK) is False:
        raise Exception("Log load dir permission error")
    log_file = USER_NAME
    log_level = parser.get(BASE, LOG_LEVEL)
    settings = get_basic_log_settings()
    settings['handlers']['info_handler']['filename'] = log_dir + '/' + log_file + '.info'
    settings['handlers']['debug_handler']['filename'] = log_dir + '/' + log_file + '.debug'
    settings['handlers']['warn_handler']['filename'] = log_dir + '/' + log_file + '.warn'
    settings['handlers']['error_handler']['filename'] = log_dir + '/' + log_file + '.error'
    if formatter == 'flume':
        settings['handlers']['info_handler']['formatter'] = formatter
        settings['handlers']['debug_handler']['formatter'] = formatter
        settings['handlers']['warn_handler']['formatter'] = formatter
        settings['handlers']['error_handler']['formatter'] = formatter
    settings['loggers'][log_file] = copy.deepcopy(settings['loggers']['dxm'])
    logging.config.dictConfig(settings)
    extra_dict = {"host": MACHINE_NAME}
    logger = logging.getLogger(log_file)
    logger.propagate = False
    if log_level == 'DEBUG':
        logger.setLevel(logging.DEBUG)
    elif log_level == 'INFO':
        logger.setLevel(logging.INFO)
    elif log_level == 'WARN':
        logger.setLevel(logging.WARN)
    elif log_level == 'ERROR':
        logger.setLevel(logging.ERROR)
    else:
        raise "unknown log level:[%s]"

    return LoggerAdapterCustomer(logger, extra_dict)


CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
try:
    logger = init_log_for_every_user(CURRENT_DIR + '/conf/mns.conf')
except:
    logger = init_log_for_every_user(CURRENT_DIR + '/conf/log.conf')

if __name__ == '__main__':
    logger.info("info message")
    logger.debug("debug message")
    logger.error("error message")
    logger.warn("warn message")
